﻿using System;
using System.Data;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
using System.IO;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
[Microsoft.SqlServer.Server.SqlUserDefinedAggregate(
    Format.UserDefined,                 //使用UserDefined 序列化格式
    IsInvariantToNulls = true,          //聚合是否与空值有关
    IsInvariantToDuplicates = false,    //聚合是否与重复值有关
    IsInvariantToOrder = false,         //聚合是否与顺序有关
    MaxByteSize = 8000)                 //聚合实例的最大大小(以字节为单位)
    ]
public class GroupAnd : IBinarySerialize
{
    /// <summary>
    /// 定义变量
    /// </summary>
    private SqlInt64 intermediateResult;
    /// <summary>
    /// 给每个要集合的新组初始化
    /// </summary>
    public void Init()
    {
        this.intermediateResult = SqlInt64.MaxValue;
    }

    /// <summary>
    /// 扫描到分组中的每一行记录时，如果某一个字符不为空,用";"追加
    /// </summary>
    /// <param name="value">记录</param>
    /// <param name="contChar">间隔符</param>
    public void Accumulate(SqlInt64 value) 
    {
        if (value.IsNull)
        {
            return;
        }
        this.intermediateResult=this.intermediateResult&value;
    }
    /// <summary>
    /// 将一个聚合组的结果合并到当前组中，合并字符
    /// </summary>
    /// <param name="other"></param>
    public void Merge(GroupAnd other)
    {
        this.intermediateResult=this.intermediateResult&other.intermediateResult;
    }

    /// <summary>
    /// 返回结果，处理最后的","
    /// </summary>
    /// <returns></returns>
    public SqlInt64 Terminate()
    {

        return this.intermediateResult;
    }

    public void Read(BinaryReader r)
    {
        intermediateResult = r.ReadInt64();
    }

    public void Write(BinaryWriter w)
    {
        w.Write(this.intermediateResult.Value);
      //  w.Write(this.intermediateResult.ToString());
    }
}
